<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<html>
<body>
	<div id="main">
		<jsp:include page="banner.jsp">
			<jsp:param name="page" value="course" />
		</jsp:include>
		<div id="courseList"></div>
	</div>
</body>
<style>
#main {
	margin: auto;
	width: 800px;
	position: relative;
}
#courseList {
	width: 100%;
}

#courseList table,
#courseList td,
#courseList th {
	border: 1px solid gray;
	border-collapse: collapse;
	text-align: center;
}

.header {
	text-align: center;
	margin: 50px auto 20px;
}

#courseList table {
	width: 100%;
}
</style>
<script>

function changeFavourite(favouriteFlag, courseID){
	var xhr = new XMLHttpRequest(),
		params = '';
	
	xhr.open('POST', 'servlet/FavouriteManage', true);
	
	xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	
	params = 'courseID=' + courseID + '&action=' + (favouriteFlag ? 'delete' : 'add');
	
	xhr.onreadystatechange = function(){
		if (xhr.readyState==4 && xhr.status==200) {
			console.log(xhr.responseText);
			loadData();
		}
	};
	
	xhr.send(params);
}

function loadData(){
var xhr = new XMLHttpRequest();
	
	xhr.open("GET", "servlet/CourseQuery", false);
	
	xhr.send("null");
	
	var data = eval(xhr.responseText);
	
	var tableHTML = "<table style='margin-top: 50px'>";
	tableHTML += '<colgroup><col width="5%"><col width="25%"><col width="50%"><col width="10%"><col width="10%"></colgroup>';
	tableHTML += '<tr><th>#</th><th>课程名称</th><th>描述</th><th>任课老师</th><th></th></tr>';
	for (var i = 0; i < data.length; i++ ){
		tableHTML += '<tr>';
		tableHTML += '<td>' + data[i].courseID + '</td>';
		tableHTML += '<td><a href="coursedetails.jsp?courseID=' + data[i].courseID + '&name=' + data[i].name + '">' + data[i].name + '</a></td>';
		tableHTML += '<td>' + data[i].description + '</td>';
		tableHTML += '<td>' + data[i].teacher + '</td>';
		tableHTML += '<td><button onclick="changeFavourite(' + data[i].favourite + ', ' + data[i].courseID + ')">' + (data[i].favourite ? '取消收藏' : '加入收藏') + '</button></td>';
		tableHTML += '</tr>';
	}
	tableHTML += '</table>';
	
	var div = document.getElementById('courseList');
	if (!div){
		div = document.createElement('div');
		div.id = 'courseList';
		document.body.appendChild(div);
	}
	div.innerHTML = tableHTML;
}

window.onload = function(){
	loadData();
};
</script>
</html>